<template>
  <el-dialog
    title="连单设置"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="handleCloseDialog"
    width="1400px"
    class="continuous-orders-dialog"
  >
    <el-descriptions class="top-container" title="连单" :column="3" border>
      <el-descriptions-item>
        <template slot="label"> 会员编号 </template>
        {{ row.id }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 登录账号 </template>
        {{ detail.phoneNo }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 余额 </template>
        {{ formatAmount(detail.balance) }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 接单位置 </template>
        <el-tag size="small"
          >{{ detail.countOrder === 0 ? 0 : detail.countOrder + 1 }}/{{
            detail.levelLimit
          }}</el-tag
        >
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 完成位置 </template>
        <el-tag size="small">{{ detail.countOrder }}/{{ detail.levelLimit }}</el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <div class="list-container" v-if="orderList.length">
      <div class="item" v-for="(item, index) in orderList" :key="index">
        <template v-if="!item.subList">
          {{ index + 1 }}. 卡位{{ item.stuckIndex }}（{{ formatAmount(item.minPrice) }}-{{ formatAmount(item.maxPrice) }}元）

          <span class="red">×{{formatAmount(item.rebateMultiple)}} 倍</span>
          <el-button type="primary" size="mini" plain @click="handleCancel(item)"
            >取消</el-button
          >
        </template>
        <template v-else>
          {{ index + 1 }}. <span v-for="(subItem,subIndex) in item.subList" :key="subIndex">卡位{{ subItem.stuckIndex }}（{{ formatAmount(subItem.minPrice) }}-{{ formatAmount(subItem.maxPrice) }}元）>></span>
          <span class="red">×{{ formatAmount(item.subList[0].rebateMultiple) }}倍</span>
          <el-button type="primary" size="mini" plain @click="handleCancel(item.subList[0])"
            >取消</el-button
          > 
        </template>
      </div>
    </div>
    <div v-else style="font-size: 14px; color: red; margin-bottom: 15px">
      暂无连单信息
    </div>

    <!-- <el-card class="filter-container" shadow="never">
      <div>
        <el-button
          style="float: right"
          type="primary"
          @click="handleSearchList()"
          size="mini"
        >
          查询搜索
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch()"
          size="mini"
        >
          重置
        </el-button>
      </div>
      <div>
        <el-form :inline="true" :model="listQuery" label-width="100px">
          <el-form-item label="最低价格：">
            <el-input
              v-model="listQuery.minPrice"
              class="input-width"
              placeholder="请输入最低价格"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="最高价格：">
            <el-input
              v-model="listQuery.maxPrice"
              class="input-width"
              placeholder="请输入最高价格"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card> -->

    <div class="table-container">
      <el-button type="danger" size="small" @click="handleAdd">设置选中</el-button>

      <el-table
        ref="adminTable"
        :data="list"
        style="width: 100%; margin-top: 10px"
        v-loading="listLoading"
        border
        size="mini"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="编号" width="100"  align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="名称" align="center">
          <template slot-scope="scope">{{ scope.row.goodsName }}</template>
        </el-table-column>
        <el-table-column label="最低投入" min-width="140" align="center">
          <template slot-scope="scope">{{ formatAmount(scope.row.minPrice) }}</template>
        </el-table-column>
        <el-table-column label="最高投入" min-width="140" align="center">
          <template slot-scope="scope">{{ formatAmount(scope.row.minPrice) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="230" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)"
              >设置</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加连单 -->
    <add-continuous-orders-dialog
      v-if="addVisible"
      :row="rows"
      @handle-confirm="handleConfirm"
      @handle-cancel="addVisible = false"
    />
    <!-- 编辑连单 -->
    <edit-continuous-orders-dialog
      v-if="updateVisible"
      :row="rows"
      @handle-confirm="handleConfirm"
      @handle-cancel="updateVisible = false"
    />
  </el-dialog>
</template>
<script>
import { createNamespacedHelpers } from "vuex";
import AddContinuousOrdersDialog from "./add-continuous-orders-dialog.vue";
import EditContinuousOrdersDialog from "./edit-continuous-orders-dialog.vue";
const { mapState } = createNamespacedHelpers("member");
import { formatAmount } from "@/utils/index";
import { getMemberOrderInfo, cancelMemberOrder } from "@/api/member/index";
import { getAllGoodsList } from "@/api/goods/index";

const defaultListQuery = {
  minPrice: "",
  maxPrice: "",
};
export default {
  components: {
    AddContinuousOrdersDialog,
    EditContinuousOrdersDialog,
  },
  data() {
    return {
      loading: false,
      visible: true,
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      addVisible: false,
      updateVisible: false,
      selectedRows: [],
      rows: {},
      detail: {},
      orderList: [],
    };
  },
  props: {
    row: {
      type: Object,
      default: {},
    },
  },
  computed: {
    ...mapState({
      statusOptions: (state) => [
        ...[{ label: "全部状态", value: null }],
        ...state.routes.statusOptions,
      ],
    }),
  },
  mounted() {
    this.getList();
    this.getGoodsList();
  },
  methods: {
    formatAmount,
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
      this.getList();
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    //添加连单
    handleAdd() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择广告!",
        });
        return;
      }
      let goodsIds = [];
      let minPrices = [];
      let maxPrices = [];
      this.selectedRows.forEach((item) => {
        goodsIds.push(item.id);
        minPrices.push(item.minPrice);
        maxPrices.push(item.maxPrice);
      });
      this.rows = { id: this.row.id, goodsIds, minPrice: minPrices.join(","), maxPrice: maxPrices.join(",") };
      this.addVisible = true;
    },
    //编辑连单
    handleEdit(data) {
      data.goodsId = data.id;
      this.rows = data;
      this.updateVisible = true;
    },

    //取消连单
    handleCancel(row) {
      cancelMemberOrder({ memberId: this.row.id,groupIndex:row.groupIndex }).then((response) => {
        this.$message({
          type: "success",
          message: "取消连单成功!",
        });
        this.getList();
      });
    },

    //新增和编辑返回
    handleConfirm() {
      this.addVisible = false;
      this.updateVisible = false;
      this.getList();
    },
    //选中连单内容
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    //关闭弹框
    handleCloseDialog() {
      this.$emit("handle-cancel");
    },
    // 格式化状态
    formatState(value) {
      return this.statusOptions.find((item) => item.value === value).label;
    },

    getList() {
      getMemberOrderInfo({ memberId: this.row.id }).then((response) => {
        this.detail = response.data.info || {};
        this.orderList = this.groupByRebateMultiple(response.data.list || []);
      });
    },
    // 获取广告列表
    getGoodsList() {
      getAllGoodsList(this.listQuery).then((response) => {
        this.list = response.data || [];
      });
    },
    groupByRebateMultiple(originalList) {
      const groups = originalList.reduce((acc, item) => {
        const key = item.groupIndex;
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(item);
        return acc;
      }, {});

      // 2. 处理分组结果：单元素组直接保留，多元素组用subList包裹
      return Object.values(groups).map((group) => {
        if (group.length === 1) {
          // 只有一个元素时，直接返回该元素
          return group[0];
        } else {
          // 多个元素时，用subList包裹
          return { subList: group };
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.top-container {
  margin-bottom: 15px;
  span {
    margin-right: 30px;
  }
}

.list-container {
  .item {
    color: #1e9fff;
    margin-bottom: 15px;
    span {
      margin-right: 10px;
    }
  }
}
.options-btns {
  position: absolute;
  left: 220px;
  top: 162px;
  z-index: 99;
}
</style>

<style lang="css">
.input-width{
  .el-input__inner{
    height: 30px!important;
    line-height: 30px!important;
  }
}
.continuous-orders-dialog{
 .el-dialog__body{
    height: 60vh!important;
  
  }
}

</style>

